package com.wfm.mianshi;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Demo1 {
    public static void main(String[] args) {
        int n = 23123;
        Integer[] arr = {2, 4, 9};
        int result = assembleLargestNumber(n, arr);
        System.out.println(result);  // 输出 29999
    }

    public static int assembleLargestNumber(int n, Integer[] arr) {
        // 将数组按降序排列，以便优先使用最大的数字
        Arrays.sort(arr, Collections.reverseOrder());

        String nStr = String.valueOf(n);
        List<Integer> res = new ArrayList<>();

        for (char digit : nStr.toCharArray()) {
            int d = Character.getNumericValue(digit);
            Integer chosenDigit = null;

            for (int i = 0; i < arr.length; i++) {
                if (arr[i] < d) {
                    chosenDigit = arr[i];
                    arr[i] = null;
                    break;
                }
            }

            if (chosenDigit == null) {
                for (int i = 0; i < arr.length; i++) {
                    if (arr[i] != null) {
                        chosenDigit = arr[i];
                        arr[i] = null;
                        break;
                    }
                }
            }

            res.add(chosenDigit);
        }

        int result = 0;
        for (int digit : res) {
            result = result * 10 + digit;
        }

        return result;
    }
}